(function(window){

	//if(!window.console) window.console = {log:function(p){}, info:function(){}, warn:function(){}};
		
	var EventCentral = new function(){

		EventCentral.INSTANCE;
		EventCentral.ALLOW_INSTANCE = false;

		EventCentral.prototype.addEventListener;
		EventCentral.prototype.removeEventListener;
		EventCentral.prototype.dispatchEvent;
//for testing only
		EventCentral.prototype.instanceTime;

		function EventCentral(){
			if(!EventCentral.ALLOW_INSTANCE) throw new Error("Singleton! - use getInstance() instead")
			EventDispatcher.initialize(this);
		}
		EventCentral.getInstance = function(){
			if(!EventCentral.INSTANCE){
				EventCentral.ALLOW_INSTANCE = true;
				EventCentral.INSTANCE = new EventCentral();
				EventCentral.INSTANCE.instanceTime = new Date();
				EventCentral.ALLOW_INSTANCE - false;
			}
			return EventCentral.INSTANCE;
		}
		return EventCentral;
	}

	var EventDispatcher = new function(){

		EventDispatcher._fEventDispatcher = undefined;

		function EventDispatcher(){

		}
		EventDispatcher._removeEventListener = function (queue, event, handler)
		{
			if (queue != undefined)
			{
				var l = queue.length;
				var i;
				for (i = 0; i < l; i++)
				{
					var o = queue[i];
					if (o == handler) {
						queue.splice(i, 1);
						return;
					}
				}
			}
		}
		EventDispatcher.initialize = function (object)
		{
			if (EventDispatcher._fEventDispatcher == undefined)
			{
				EventDispatcher._fEventDispatcher = new EventDispatcher();
			}
			object.addEventListener = EventDispatcher._fEventDispatcher.addEventListener;
			object.removeEventListener = EventDispatcher._fEventDispatcher.removeEventListener;
			object.dispatchEvent = EventDispatcher._fEventDispatcher.dispatchEvent;
			object.dispatchQueue = EventDispatcher._fEventDispatcher.dispatchQueue;
		}

		EventDispatcher.prototype.dispatchQueue = function(queueObj, eventObj)
		{
			var queueName = "__q_" + eventObj.type;
			var queue = queueObj[queueName];
			if (queue != undefined)
			{
				var i;
				for (i in queue)
				{
					var o = queue[i];
					o.apply(queueObj, [eventObj]);
				}
			}
		}

		EventDispatcher.prototype.dispatchEvent = function(eventObj)
		{
			if (eventObj.target == undefined)
				eventObj.target = this;
			this.dispatchQueue(this, eventObj);
		}

		EventDispatcher.prototype.addEventListener = function(event, handler)
		{
			var queueName = "__q_" + event;
			if (this[queueName] == undefined)
			{
				this[queueName] = new Array();
			}
			EventDispatcher._removeEventListener(this[queueName], event, handler);
			this[queueName].push(handler);
		}
		
		EventDispatcher.prototype.removeEventListener = function(event, handler)
		{
			var queueName = "__q_" + event;
			EventDispatcher._removeEventListener(this[queueName], event, handler);
		}
		return EventDispatcher;
	}

	if(!window.EventCentral) window.EventCentral = EventCentral;
}(window));	
